import time
from io import BytesIO
from time import sleep

import pytesseract
from PIL import Image

from selenium.webdriver.common.by import By
from Utils import ShoppingDriver

# 配置Tesseract路径（根据实际情况修改）
pytesseract.pytesseract.tesseract_cmd = r'D:\Program Files\Tesseract-OCR\tesseract.exe'

username="body > div.body-content-container > div.body-content-formal-container > div.am-g.user-login-container.am-padding-top-0.am-padding-bottom-0.theme-data-edit-event > div > div.am-container > div.am-u-sm-12.am-u-md-6.am-u-lg-4.user-right-container > div.am-radius-lg.am-background-white > div > div.am-tabs-bd.am-border-0 > div.am-tab-panel.am-active > form > div:nth-child(1) > input"
password="body > div.body-content-container > div.body-content-formal-container > div.am-g.user-login-container.am-padding-top-0.am-padding-bottom-0.theme-data-edit-event > div > div.am-container > div.am-u-sm-12.am-u-md-6.am-u-lg-4.user-right-container > div.am-radius-lg.am-background-white > div > div.am-tabs-bd.am-border-0 > div.am-tab-panel.am-active > form > div:nth-child(2) > input"
verify_code="body > div.body-content-container > div.body-content-formal-container > div.am-g.user-login-container.am-padding-top-0.am-padding-bottom-0.theme-data-edit-event > div > div.am-container > div.am-u-sm-12.am-u-md-6.am-u-lg-4.user-right-container > div.am-radius-lg.am-background-white > div > div.am-tabs-bd.am-border-0 > div.am-tab-panel.am-active > form > div:nth-child(3) > input"

class ShoppingLogin:
   url=""
   driver=""
def __init__(self):
    self.driver=ShoppingDriver.driver
    self.url="http://8.155.1.153/?s=user/logininfo.html"
    self.driver.get(self.url)
    self.driver.fullscreen_window()

def getverifycode(self):
    try:
        # 定位元素
        element = self.driver.find_element(By.CSS_SELECTOR, "#form-verify-img")
        # 截图验证码的元素(Selenium 自带方法,直接对元素截图，比全图截图精准)
        img_bytes = element.screenshot_as_png
        img_element = Image.open(BytesIO(img_bytes))
        # 用OCR工具识别图片
        # 预处理：转为灰度图
        img_element = img_element.convert("L")
        # OCR 识别（限制识别范围：只识别数字）
        img_text = pytesseract.image_to_string(
            img_element,
            config="--psm 10 -c tessedit_char_whitelist=0123456789"
        )
        # 清洗结果（去掉空白、换行符）
        img_text = img_text.strip()
        return img_text
    except Exception as e:
        print("getverifycode failed")
        print(e)
        # 添加截图
        ShoppingDriver.getScreeShot()
        raise

def LoginSuccess(self):
    time.sleep(1)
    try:
        self.driver.find_element(By.CSS_SELECTOR, username).clear()
        self.driver.find_element(By.CSS_SELECTOR, password).clear()
        self.driver.find_element(By.CSS_SELECTOR, verify_code).clear()
        #输入框输入账号
        self.driver.find_element(By.CSS_SELECTOR, username).send_keys("xiaohua")
        #输入框输入密码
        self.driver.find_element(By.CSS_SELECTOR, password).send_keys("bite123")
        #输入框输入验证码
        # 获取验证码
        img_text = ShoppingLogin.getverifycode(self)
        # 输入验证码
        self.driver.find_element(By.CSS_SELECTOR, verify_code).send_keys(img_text)
        #点击登录
        self.driver.find_element(By.CSS_SELECTOR, "body > div.body-content-container > div.body-content-formal-container > div.am-g.user-login-container.am-padding-top-0.am-padding-bottom-0.theme-data-edit-event > div > div.am-container > div.am-u-sm-12.am-u-md-6.am-u-lg-4.user-right-container > div.am-radius-lg.am-background-white > div > div.am-tabs-bd.am-border-0 > div.am-tab-panel.am-active > form > div.am-form-group.am-form-group-refreshing.am-margin-top-lg.am-padding-0 > button").click()
        #进入首页后，验证网站logo，确认是不是进入了首页
        self.driver.find_element(By.CSS_SELECTOR, "body > div.body-content-container > div.body-content-formal-container > div.nav-seasrch.header-nav-simple.am-hide-sm-only > div > div.logo.theme-data-edit-event > a > img")
    except Exception as e:
        print("LoginSuccess failed")
        print(e)
        #添加截图
        ShoppingDriver.getScreeShot()
        raise


def LoginFail(self):
    try:
        time.sleep(1)
        # 获取验证码
        img_text = ShoppingLogin.getverifycode(self)
        test_dic = [
            {"desc": "用户名长度<2字符登录", "username": "a", "password": "bit12344321..",
             "verify_code": img_text},
            {"desc": "用户名长度>18字符登录", "username": "a" * 19, "password": "bit12344321..",
             "verify_code": img_text},
            {"desc": "不写用户名登录", "username": "", "password": "bit12344321..",
             "verify_code": img_text},
            {"desc": "错误的用户名登录", "username": "dz669", "password": "bit12344321..",
             "verify_code": img_text},
            {"desc": "密码长度<6字符登录", "username": "dz000", "password": "123",
             "verify_code": img_text},
            {"desc": "密码长度>18字符登录", "username": "dz000", "password": "a" * 19,
             "verify_code": img_text},
            {"desc": "不写密码登录", "username": "dz000", "password": "",
             "verify_code": img_text},
            {"desc": "错误的密码登录", "username": "dz000", "password": "bit1234321..",
             "verify_code": img_text},
            {"desc": "不写验证码登录", "username": "dz000", "password": "bit12344321..",
             "verify_code": ""},
            {"desc": "错误的验证码登录", "username": "dz000", "password": "bit12344321..",
             "verify_code": "wrong"},
        ]

        for dic in test_dic:
            #print(f"执行测试用例: {dic['desc']}")

            # 清空输入框
            self.driver.find_element(By.CSS_SELECTOR, username).clear()
            self.driver.find_element(By.CSS_SELECTOR, password).clear()
            self.driver.find_element(By.CSS_SELECTOR, verify_code).clear()
            time.sleep(1)

            # 输入用户名
            if dic["username"]:
                self.driver.find_element(By.CSS_SELECTOR, username).send_keys(dic["username"])
            # 输入密码
            if dic["password"]:
                self.driver.find_element(By.CSS_SELECTOR, password).send_keys(dic["password"])
            # 输入验证码
            if dic["verify_code"]:
                self.driver.find_element(By.CSS_SELECTOR, verify_code).send_keys(dic["verify_code"])

            # 点击登录
            self.driver.find_element(By.CSS_SELECTOR,
            "body > div.body-content-container > div.body-content-formal-container > div.am-g.user-login-container.am-padding-top-0.am-padding-bottom-0.theme-data-edit-event > div > div.am-container > div.am-u-sm-12.am-u-md-6.am-u-lg-4.user-right-container > div.am-radius-lg.am-background-white > div > div.am-tabs-bd.am-border-0 > div.am-tab-panel.am-active > form > div.am-form-group.am-form-group-refreshing.am-margin-top-lg.am-padding-0 > button").click()
            # 登录失败后，验证网站logo，确认是不是还在登录界面
            self.driver.find_element(By.CSS_SELECTOR,"body > div.body-content-container > div.body-content-formal-container > div.nav-seasrch.header-nav-simple > div > p.login-title.am-fl.am-vertical-align-middle.am-margin-left-main")

    except Exception as e:
        print("LoginFail failed")
        print(e)
        # 添加截图
        ShoppingDriver.getScreeShot()
        raise
